package com.chen.controller;

import com.chen.common.Constants;
import com.chen.entity.User;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @author chenchao
 * @date 2022/7/27 14:57
 */
@Component
public class MailReceiver {

    private static final Logger log = LoggerFactory.getLogger(MailReceiver.class);

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private MailProperties mailProperties;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TemplateEngine templateEngine;

    @RabbitListener(queues = Constants.MMAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel) {
//        获取传递的参数
        User user = (User) message.getPayload();
        MessageHeaders headers = message.getHeaders();
//        获取消息序号
        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);

        String msgId = (String) headers.get("spring_returned_message_correlation");

//        创建一个hash
        HashOperations hashOperations = redisTemplate.opsForHash();

        try {
            if (hashOperations.entries("mail_log").containsKey(msgId)) {
                log.error("消息已经被消费==========>{}", msgId);
//    手动确让消息，取消多条消息
                channel.basicAck(tag, false);
                return;
            }
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
//            发件人
            helper.setFrom(mailProperties.getUsername());
            helper.setTo(user.getEmail());
            helper.setSubject("欢迎邮件");
            helper.setSentDate(new Date());
//            内容
            Context context = new Context();
            context.setVariable("username", user.getUsername());
            context.setVariable("nickname", user.getNickname());
            context.setVariable("role", user.getRole());
            String mail = templateEngine.process("mail", context);
            helper.setText(mail, true);
            javaMailSender.send(mimeMessage);
            log.info("消息发送成功=====================》");
//            将消息id存入redis
            hashOperations.put("mail_log", msgId, "ok");
//手动确认
            channel.basicAck(tag, false);
        } catch (Exception e) {
            /**
             * 手动确让消息
             * 消息序列
             * 是否确认多条
             * 是否退回队列
             */
            try {
                channel.basicNack(tag, false, true);
            } catch (IOException e1) {
                log.error("邮件发送失败===============》" + e.getMessage());
                e1.printStackTrace();
            }
            log.error("邮件发送失败===============》" + e.getMessage());
        }
    }

}
